package com.duan.nowcoder.community.controller;


import com.alibaba.fastjson.JSONObject;
import com.duan.nowcoder.community.entity.Event;
import com.duan.nowcoder.community.entity.Message;
import com.duan.nowcoder.community.entity.Page;
import com.duan.nowcoder.community.entity.User;
import com.duan.nowcoder.community.service.MessageService;
import com.duan.nowcoder.community.service.UserService;
import com.duan.nowcoder.community.util.CommunityConstant;
import com.duan.nowcoder.community.util.CommunityUtil;
import com.duan.nowcoder.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

@Controller
@RequestMapping("/letter")
public class    MessageController implements CommunityConstant {
    @Autowired
    private MessageService messageService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public String getLetterList(Model model, Page page) {
        User user = hostHolder.getUser();
        page.setLimit(5);
        page.setPath("/letter/list");
        page.setRows(messageService.findConversationCount(user.getId()));

        List<Message> messages = messageService.findConversations(user.getId(), page.getOffset(), page.getLimit());
        List<Map<String, Object>> conversations = new ArrayList<>();
        for (Message message : messages) {
            Map<String, Object> map = new HashMap<>();
            map.put("message", message);
            map.put("unreadCount", messageService.findLetterUnreadCount(user.getId(), message.getConversationId()));
            int targetId = message.getFromId() == user.getId() ? message.getToId() : message.getFromId();
            map.put("target", userService.findUserById(targetId));
            map.put("messageCount", messageService.findLetterCount(message.getConversationId()));
            conversations.add(map);
        }
        model.addAttribute("wholeUnreadCount", messageService.findLetterUnreadCount(user.getId(), null));
        int unreadNoticeCount = messageService.findAllUnreadNoticeCount(user.getId());
        model.addAttribute("wholeUnreadNoticeCount",unreadNoticeCount);
        model.addAttribute("conversations", conversations);

        return "/site/letter";
    }

    @GetMapping("/detail/{conversationId}")
    public String getConversationDetail(Model model, @PathVariable("conversationId") String conversationId, Page page) {
        page.setLimit(5);
        page.setPath("/letter/detail/" + conversationId);
        page.setRows(messageService.findLetterCount(conversationId));
        List<Message> letters = messageService.findLetters(conversationId, page.getOffset(), page.getLimit());
        List<Map<String, Object>> message = new ArrayList<>();
        List<Integer> toReadList = new ArrayList<>();
        for (Message letter : letters) {
            Map<String, Object> map = new HashMap<>();
            User from = userService.findUserById(letter.getFromId());
            map.put("from", from);
            map.put("letter", letter);
            message.add(map);
            if (letter.getStatus() == 0 && letter.getToId() == hostHolder.getUser().getId()) {
                toReadList.add(letter.getId());
            }
        }
        model.addAttribute("messages", message);
        User targetUser = getTargetUser(letters.get(0).getConversationId());
        model.addAttribute("targetUsername", targetUser.getUsername());
        if (!toReadList.isEmpty()) {
            messageService.updateStatus(toReadList, 1);
        }
        return "/site/letter-detail";
    }

    public User getTargetUser(String conversationId) {
        String[] s = conversationId.split("_");
        int s1 = Integer.parseInt(s[0]);
        int s2 = Integer.parseInt(s[1]);
        int id = hostHolder.getUser().getId();
        id = s1 == id ? s2 : s1;
        return userService.findUserById(id);
    }

    @PostMapping("/send")
    @ResponseBody
    public String sendLetter(String toName, String content) {
        User target = userService.findUserByName(toName);
        if (target == null) {
            return CommunityUtil.getJSONString(0, "该用户不存在！");
        }
        Message message = new Message();
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(target.getId());
        if (message.getFromId() < message.getToId()) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        } else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }
        message.setContent(content);
        message.setCreateTime(new Date());
        messageService.addLetter(message);

        return CommunityUtil.getJSONString(1, "发送成功！");
    }

    @GetMapping("/notice")
    private String getNotice(Model model) {
        User user = hostHolder.getUser();

        model.addAttribute("comment", getTopicMap(TOPIC_COMMENT));
        model.addAttribute("like", getTopicMap(TOPIC_LIKE));
        model.addAttribute("follow", getTopicMap(TOPIC_FOLLOW));
        model.addAttribute("unreadLetterCount",messageService.findLetterUnreadCount(user.getId(), null));
        model.addAttribute("unreadNoticeCount",messageService.findAllUnreadNoticeCount(user.getId()));


        return "/site/notice";

    }

    private Map<String, Object> getTopicMap(String topic) {
        int userId = hostHolder.getUser().getId();
        Map<String, Object> map = new HashMap<>();
        Message last = messageService.findLastNotice(userId, topic);
        if (last == null) {
            map.put("unreadCount", 0);
            map.put("lastTime", 0);
            map.put("username", null);
            map.put("count", 0);
            return map;
        }
        //未读消息数
        map.put("unreadCount", messageService.findUnreaderNoticeCount(userId, topic));
        //最后一条消息的用户名
        Event event = JSONObject.parseObject(HtmlUtils.htmlUnescape(last.getContent()), Event.class);//此处要用htmlUnescape进行反转义，否则无法识别
        map.put("username", userService.findUserById(event.getUserId()).getUsername());
        //最后一条消息的时间
        map.put("lastTime", last.getCreateTime());
        //总共的消息数
        map.put("count", messageService.findNoticeCount(userId, topic));
        //把剩余的data数据存入
        return map;
    }

    @GetMapping("/notice/{topic}")
    public String getNoticeDetail(@PathVariable("topic") String topic, Model model, Page page) {
        int userId = hostHolder.getUser().getId();
        page.setRows(messageService.findNoticeCount(userId,topic));
        page.setPath("/letter/notice/"+topic);
        page.setLimit(10);
        List<Message> notices = messageService.findNoticeByTopic(userId, topic);
        List<Object> noticesVO = new ArrayList<>();
        List<Integer> updataIds = new ArrayList<>();
        if (notices != null) {
            for (Message notice : notices) {
                updataIds.add(notice.getId());
                Map<String, Object> map = new HashMap<>();
                Event event = JSONObject.parseObject(HtmlUtils.htmlUnescape(notice.getContent()), Event.class);
                //当前用户的名字
                map.put("myName", hostHolder.getUser().getUsername());
                //评论用户名字
                map.put("username", userService.findUserById(event.getUserId()).getUsername());
                //评论时间
                map.put("time", notice.getCreateTime());
                //做的动作
                switch (topic) {
                    case TOPIC_LIKE:
                        if (event.getEntityType() == ENTITY_TYPE_POST) {
                            map.put("do", "赞了您的帖子");
                        } else if (event.getEntityType() == ENTITY_TYPE_COMMENT) {
                            map.put("do", "赞了您的回复");
                        }
                        //目标链接
                        map.put("link", "/discuss/detail/"+event.getEntityId());
                        break;
                    case TOPIC_COMMENT:
                        if (event.getEntityType() == ENTITY_TYPE_COMMENT) {
                            map.put("do", "评论了您的帖子");
                        } else if (event.getEntityType() == ENTITY_TYPE_POST) {
                            map.put("do", "回复了您的评论");
                        }
                        map.put("link", "/discuss/detail/"+event.getEntityId());
                        break;
                    case TOPIC_FOLLOW:
                        map.put("do", "关注了您");
                        map.put("link", "/user/profile/"+event.getUserId());
                        break;
                }
                noticesVO.add(map);
            }
        }
        model.addAttribute("notices", noticesVO);
        //修改已读
        messageService.updateStatus(updataIds,1);
        return "/site/notice-detail";
    }
}
